<template>
  <div v-if="dialogVisible" class="modal">
    <div class="modal-content">
      <h3>上传文件</h3>

      <!-- Tab选择器 -->
      <div class="tabs">
        <div class="tab-header">
          <div
              :class="{ active: activeTab === 'file' }"
              class="tab-item"
              @click="activeTab = 'file'">
            本地文件
          </div>
          <div
              :class="{ active: activeTab === 'url' }"
              class="tab-item"
              @click="activeTab = 'url'">
            URL上传
          </div>
          <div
              :class="{ active: activeTab === 'other' }"
              class="tab-item"
              @click="activeTab = 'other'">
            其他方式
          </div>
        </div>

        <!-- Tab内容区域 -->
        <div class="tab-content">
          <!-- 第一个Tab：本地文件上传 -->
          <div v-if="activeTab === 'file'" class="tab-panel">
            <div :class="{ 'dragover': isDragging }"
                 class="upload-area"
                 @dblclick="triggerFileInput"
                 @paste="handlePasteFile"
                 @dragover.prevent="dragOver"
                 @drop.prevent="handleDropFile"
                 @dragleave.prevent="dragLeave">
              >
              <input
                  ref="fileInput"
                  style="display: none"
                  type="file"
                  @change="handleFileSelect"
              >
              <div class="upload-icon">
                <svg fill="none" height="48" viewBox="0 0 24 24" width="48" xmlns="http://www.w3.org/2000/svg">
                  <path d="M12 15V3M12 3L8 7M12 3L16 7" stroke="#4CAF50" stroke-linecap="round" stroke-width="2"/>
                  <path d="M20 17V19C20 20.1046 19.1046 21 18 21H6C4.89543 21 4 20.1046 4 19V17" stroke="#4CAF50"
                        stroke-linecap="round" stroke-width="2"/>
                </svg>
              </div>
              <p class="upload-text"> 双击、拖拽文件到此处上传，或者点击框内空白直接粘贴图片</p>
              <p class="upload-hint">支持单个文件上传，最大2GB</p>
              <div v-if="selectedFile" class="selected-file">
                <div class="file-info">
                  <span class="file-icon">📄</span>
                  <div class="file-details">
                    <div class="file-name">{{ selectedFile.name }}</div>
                    <div class="file-size">{{ formatFileSize(selectedFile.size) }}</div>
                  </div>
                </div>
                <button class="remove-file-button" @click.stop="removeSelectedFile">
                  <svg fill="none" height="16" viewBox="0 0 24 24" width="16" xmlns="http://www.w3.org/2000/svg">
                    <path d="M18 6L6 18M6 6L18 18" stroke="#ff4444" stroke-linecap="round" stroke-width="2"/>
                  </svg>
                </button>
              </div>
            </div>
          </div>

          <!-- 第二个Tab：URL上传 -->
          <div v-if="activeTab === 'url'" class="tab-panel">
            <div class="url-upload-area">
              <div class="upload-icon">
                <svg fill="none" height="48" viewBox="0 0 24 24" width="48" xmlns="http://www.w3.org/2000/svg">
                  <path d="M12 15V3M12 3L8 7M12 3L16 7" stroke="#2196F3" stroke-linecap="round" stroke-width="2"/>
                  <path d="M20 17V19C20 20.1046 19.1046 21 18 21H6C4.89543 21 4 20.1046 4 19V17" stroke="#2196F3"
                        stroke-linecap="round" stroke-width="2"/>
                  <path d="M12 17H16M12 21H16" stroke="#2196F3" stroke-linecap="round" stroke-width="2"/>
                </svg>
              </div>
              <p class="upload-text">输入文件URL地址进行上传</p>
              <div class="url-input-area">
                <input
                    v-model="fileUrl"
                    :disabled="uploading"
                    class="url-input"
                    placeholder="请输入文件URL地址"
                    type="text"
                >
              </div>
            </div>
          </div>

          <!-- 第三个Tab：功能暂定 -->
          <div v-if="activeTab === 'other'" class="tab-panel">
            <div class="other-upload-area">
              <div class="upload-icon">
                <svg fill="none" height="48" viewBox="0 0 24 24" width="48" xmlns="http://www.w3.org/2000/svg">
                  <circle cx="12" cy="12" r="10" stroke="#9E9E9E" stroke-width="2"/>
                  <path d="M12 8V12L14 14" stroke="#9E9E9E" stroke-linecap="round" stroke-width="2"/>
                </svg>
              </div>
              <p class="upload-text">其他上传方式正在开发中</p>
              <p class="upload-hint">敬请期待...</p>
            </div>
          </div>
        </div>
      <div class="file-name-input">
        <label>自定义文件名:</label>
        <input
            v-model="customFileName"
            :disabled="uploading"
            placeholder="留空则使用原文件名"
            type="text"
        >
      </div>
      <div class="modal-actions">
        <button :disabled="uploading" @click="cancelUpload">取消</button>
        <button
            :class="{ 'uploading': uploading }"
            :disabled="(!selectedFile && activeTab == 'file') || (!(fileUrl && customFileName) && activeTab == 'url') || uploading"
            class="upload-button"
            @click="confirmUpload"
        >
          <span v-if="!uploading">上传文件</span>
          <span v-else class="uploading-text">
            <span class="spinner"></span>
            上传中 {{ uploadProgress }}%
          </span>
        </button>
      </div>
    </div>
    </div>
  </div>

</template>

<script lang="ts" setup>
import {
  confirmUploadFile,
  customFileName,
  dragLeave,
  dragOver,
  handleDropFile,
  handleFileSelect, handlePastePic,
  isDragging, resetUploadState, selectedFile, uploading, uploadProgress
} from "@/views/documentManager/components/ts/uploadFile";
import {currentBucketName, currentPath, formatFileSize} from "@/views/documentManager/components/ts/FileBrowser";
import {onMounted, ref, watch} from "vue";
import {message} from "@/utils/ElmessasgeUtils";
import {uploadFileViaUrl} from "@/api/documentManage/minioManager2";

// Tab相关状态
const activeTab = ref<'file' | 'url' | 'other'>('file');
const fileUrl = ref('');

// 当切换Tab时，重置上传状态
watch(activeTab, (newTab) => {
  resetUploadState();
  if (newTab === 'url') {
    fileUrl.value = '';
  }
});

// URL上传的函数
const confirmUploadFromUrl = async () => {
  // 验证URL输入
  if (!fileUrl.value || uploading.value) {
    message('请输入有效的URL地址', 'warning');
    return;
  }

  if (!customFileName.value || uploading.value) {
    message('请输入有效的URL文件名', 'warning');
    return;
  }

  try {
    // 尝试解析URL，确保格式正确
    new URL(fileUrl.value);
  } catch (e) {
    message('请输入有效的URL地址', 'error');
    return;
  }

  uploading.value = true;

  try {
    uploadProgress.value = 0
    let res: any = await uploadFileViaUrl({
      bucket: currentBucketName.value,
      url: fileUrl.value,
      objectName: `${currentPath.value}/${customFileName.value}`,
    })
    uploadProgress.value = 100;

    if (res.data.code === 200) {
      message('文件已成功从URL上传', 'success');
    } else {
      message("上传文件失败" + res.data.msg, 'error');
    }

    // 上传成功后清理状态并关闭对话框
    closeDialog();
    resetUploadState();
    fileUrl.value = '';
    emit("uploadFile");

  } catch (err: any) {
    console.error('URL上传错误:', err);
    message(err.response?.data?.message || err.message || 'URL上传过程中发生错误', 'error');
  } finally {
    uploading.value = false;
  }
};


// 定义props和emit
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:dialogVisible', 'uploadFile']);

// 关闭对话框
const closeDialog = () => {
  emit('update:dialogVisible', false)
}

// 上传相关
const fileInput = ref<HTMLInputElement | null>(null);

// 取消上传, 隐藏对话框
const cancelUpload = () => {
  if (!uploading.value) {
    if (fileInput.value) {
      fileInput.value.value = '';
    }
    closeDialog()
  }
};

// 双击上传文件框 文件选择
const triggerFileInput = () => {
  if (!uploading.value) {
    fileInput.value?.click();
  }
};

// 移除已选文件
const removeSelectedFile = () => {
  if (!uploading.value) {
    selectedFile.value = null;
    if (fileInput.value) {
      fileInput.value.value = '';
    }
  }
};

// 确认上传文件
const confirmUpload = async () => {
  if (activeTab.value === 'file') {
    await confirmUploadFile(currentPath.value, async () => {
      closeDialog()
      resetUploadState()
      if (fileInput.value) {
        fileInput.value.value = '';
      }
      emit("uploadFile")
    })
  } else if (activeTab.value === 'url') {
    await confirmUploadFromUrl();
  } else if (activeTab.value === 'other') {
    message('此功能尚未实现', 'info');
  }
}

// 处理粘贴 图片 的方法
const handlePasteFile = async (event: ClipboardEvent) => {
  if (fileInput.value) {
    fileInput.value.value = '';
  }

  await handlePastePic(event);
};


onMounted(() => {
  resetUploadState();

  if (fileInput.value) {
    fileInput.value.value = '';
  }
})



</script>

<style scoped>

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1001;
}

/* Tab相关样式 */
.tabs {
  width: 100%;
  margin-bottom: 16px;
}

.tab-header {
  display: flex;
  border-bottom: 2px solid #e0e0e0;
}

.tab-item {
  padding: 8px 16px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
  font-size: 14px;
  color: #666;
}

.tab-item:hover {
  color: #4CAF50;
}

.tab-item.active {
  color: #4CAF50;
  border-bottom-color: #4CAF50;
  font-weight: 500;
}

.tab-content {
  margin-top: 16px;
}

.tab-panel {
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-content {
  background-color: white;
  padding: 24px;
  border-radius: 8px;
  min-width: 500px; /* 增加最小宽度 */
  width: 500px; /* 设置固定宽度 */
  max-width: 90%;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-content h3 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #333;
}

.modal-content input {
  width: 100%;
  padding: 10px;
  margin: 10px 0;
  box-sizing: border-box;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.modal-content input:focus {
  outline: none;
  border-color: #4CAF50;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.modal-actions button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.modal-actions button:not(.danger) {
  background-color: #f0f0f0;
}

.modal-actions button:not(.danger):hover {
  background-color: #e0e0e0;
}

.modal-actions button.danger {
  background-color: #f44336;
  color: white;
}

.modal-actions button.danger:hover {
  background-color: #d32f2f;
}

.preview-modal .modal-content {
  max-width: 90%;
  max-height: 90vh;
  width: 800px;
  display: flex;
  flex-direction: column;
}


.upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  margin: 16px 0;
  transition: all 0.3s;
  min-height: 250px; /* 确保与其他上传区域高度一致 */
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.upload-area:hover {
  border-color: #4CAF50;
  background-color: #f8f8f8;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.selected-file {
  margin-top: 10px;
  padding: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.remove-file-button {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.remove-file-button:hover {
  color: #f44336;
}

.file-name-input {
  margin: 16px 0;
}

.file-name-input label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.file-name-input input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

/* URL上传相关样式 */
.url-upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 30px;
  text-align: center;
  margin: 16px 0;
  background-color: #fafafa;
  min-height: 250px; /* 确保与文件上传区域高度一致 */
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.url-input-area {
  margin-top: 20px;
  text-align: left;
  width: 100%;
}

.url-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.url-input:focus {
  outline: none;
  border-color: #2196F3;
  box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1);
}

.url-file-name {
  margin-top: 8px;
  padding: 6px 10px;
  background-color: #e3f2fd;
  border-radius: 4px;
  font-size: 12px;
  color: #1565c0;
}

/* 其他上传方式相关样式 */
.other-upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 30px;
  text-align: center;
  margin: 16px 0;
  min-height: 250px; /* 确保与文件上传区域高度一致 */
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

</style>